<?php


namespace App\Services;


use App\Models\Order;
use App\Models\WxUser;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Support\Facades\DB;

class OrderService
{
    /**
     * @Notes:创建订单
     * @Author:Planb,
     * @Date: 2022/11/12,
     * @Time: 9:35,
     */
    public static function createOrder($uid,$price,$orderType,$houseId){
        DB::beginTransaction();
        try {
            $userInfo = WxUser::where('id',$uid)->first();
            Order::insert([
                'order_sn'=>(new Snowflake())->id(),
                'uid'=>$uid,
                'phone'=>$userInfo['user_phone'],
                'order_type'=>$orderType,
                'pay_price'=>$price,
                'house_id'=>$houseId,
                'pay_time'=>date('Y-m-d'),
                'created_at'=>date('Y-m-d H:i:s')
        ]);
            DB::commit();
            return StatusNumber::SUCCESS;
        }catch (\Exception $exception){
            DB::rollBack();
            return $exception->getMessage();
        }
    }

    /**
     * @Notes:获取订单信息
     * @Author:Planb,
     * @Date: 2022/11/12,
     * @Time: 10:21,
     */
    public static function getOrderInfo($uid,$houseId){
        $orderInfo = Order::where('uid',$uid)->where('house_id',$houseId)->orderby('created_at','desc')->first();
        if ($orderInfo){
            return $orderInfo;
        }else{
            return false;
        }
    }

    /**
     * @Notes:获取订单明细
     * @Author:Planb,
     * @Date: 2022/11/15,
     * @Time: 15:03,
     */
    public static function getPayDetail($uid,$date){
        $date = $date.'-01';
        //月初第一天
        $dateBegin = date('Y-m-01',strtotime($date));
        //月初最后一天
        $dateEnd = date('Y-m-t',strtotime($date));
        $order = Order::where('uid',$uid)->whereBetween('created_at',[$date,$dateEnd])->get()->toArray();
        if ($order){
            $currentPrice = 0;
            foreach ($order as $k=>$value){
                $currentPrice = $currentPrice+$value['pay_price'];
                $payDetail[$k]['pay_price']=$value['pay_price'];
                $payDetail[$k]['pay_time']=$value['created_at'];
                $payDetail[$k]['order_type']=$value['order_type']==1?'支付宝支付':'微信支付';
            }
            if ($payDetail && $currentPrice){
                return [
                    'pay_detail'=>$payDetail,
                    'current_price'=>$currentPrice
                ];
            }else{
                return false;
            }
        }else{
            return false;
        }



    }
}
